﻿using LightingPlatform.TCP;
using LightingPlatform.Tools;
using LightingPlatform.ViewModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace LightingPlatform
{
    public partial class MainPage : UserControl, INotifyPropertyChanged
    {
        private ResItem _emptyItem;
        private ResItem EmptyItem
        {
            get
            {
                if (_emptyItem == null)
                {
                    ResItem.Builder builder = new ResItem.Builder();
                    builder.SetItemName("全部");
                    _emptyItem = builder.Build();
                }
                return _emptyItem;
            }
        }

        private PageLevel _targetPage;

        public PageLevel TargetPage
        {
            get { return _targetPage; }
            set
            {
                _targetPage = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("TargetPage"));
            }
        }
        

        public MainPage()
        {
            InitializeComponent();

            Navigation.Navigated += Navigation_Navigated;
            AddBtn.Click += AddBtn_Click;
            BackLink.Click += BackLink_Click;
            NextLink.Click += NextLink_Click;
            EditBtn.Click += EditBtn_Click;
            SearchBtn.Click += SearchBtn_Click;
            UserBtn.Click += UserBtn_Click;
            DeleteBtn.Click += DeleteBtn_Click;
            ExportExcelBtn.Click += ExportExcelBtn_Click;
            ExportPdfBtn.Click += ExportPdfBtn_Click;
            ToolBar.DataContext = this;

            Navigation.Navigate(new Uri("/View/LightingNavigation.xaml", UriKind.RelativeOrAbsolute));
            GetStaticResource();
            GetLabels();
        }

        private IList<ResItem> InsertEmptyItem(IEnumerable<ResItem> items)
        {
            List<ResItem> list = new List<ResItem>();
            list.AddRange(items);
            list.Insert(0, EmptyItem);
            return list;
        }

        private async void GetStaticResource()
        {
            ResourceProvider resPovider = new ResourceProvider();
            await resPovider.GetStaticResource();

            UseArea.ItemsSource = InsertEmptyItem(resPovider.UseArea);
            ProdType.ItemsSource = InsertEmptyItem(resPovider.ProdTypes);
            LightingType.ItemsSource = InsertEmptyItem(resPovider.LightingType);
            SetupType.ItemsSource = InsertEmptyItem(resPovider.SetupType);
        }

        private async void GetLabels()
        {
            WebServiceProxy proxy = new WebServiceProxy();
            string names = await proxy.SearchProdName();


            List<ResItem> list = new List<ResItem>();
            if (!string.IsNullOrEmpty(names))
            {
                foreach(string str in names.Split(','))
                {
                    ResItem.Builder builder = new ResItem.Builder();
                    builder.SetItemName(str);
                    list.Add(builder.Build());
                }
            }

            list.Insert(0, EmptyItem);
            ProductLable.ItemsSource = list;
        }

        private void LoginBtn_Click(object sender, RoutedEventArgs e)
        {
            LoginWindow window = new LoginWindow();
            window.Closed += (sender1, e1) =>
            {
                if (window.DialogResult.HasValue && window.DialogResult.Value)
                    TargetPage = _targetPage;
            };
            window.Show();
        }

        private void UserBtn_Click(object sender, RoutedEventArgs e)
        {
            //UserManagerWindow window = new UserManagerWindow();
            //window.Show();
        }












        private void ExportPdfBtn_Click(object sender, RoutedEventArgs e)
        {
            if (Navigation.Content is IExportData)
            {
                IExportData page = (IExportData)Navigation.Content;
                page.ExportToPdf();
            }
        }

        private void ExportExcelBtn_Click(object sender, RoutedEventArgs e)
        {
            if (Navigation.Content is IExportData)
            {
                IExportData page = (IExportData)Navigation.Content;
                page.ExportToExcel();
            }
        }

        private void AddBtn_Click(object sender, RoutedEventArgs e)
        {
            //LightingContext.Singleton.QueryParameter5 = null;
            //LightingContext.Singleton.Navigation.Navigate(new Uri("/View/Level5/LightingView.xaml", UriKind.RelativeOrAbsolute));
        }



        private async void DeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            //if (Navigation.Content is LightingVersionView)
            //{
            //    byte[] response = await TCPClient.Current.Call((int)CommandType.DeleteLighting, Encoding.UTF8.GetBytes(LightingContext.Singleton.QueryParameter4.ID));
            //    if (response != null &&  response.Length > 0 && response[0] == (byte)1)
            //    {
            //        MessageHelper.ShowMessage("删除灯具成功。");
            //        if (Navigation.CanGoBack)
            //            Navigation.GoBack();
            //    }
            //    else
            //    {
            //        MessageHelper.ShowError("删除灯具失败。");
            //    }
            //}
        }

        private void EditBtn_Click(object sender, RoutedEventArgs e)
        {
            //if (Navigation.Content is LightingVersionView)
            //{
            //    LightingContext.Singleton.QueryParameter5 = LightingContext.Singleton.QueryParameter4.ID;
            //    LightingContext.Singleton.Navigation.Navigate(new Uri("/View/Level5/LightingView.xaml", UriKind.RelativeOrAbsolute));
            //}
        }

        private void BackLink_Click(object sender, RoutedEventArgs e)
        {
            Navigation.GoBack();
        }

        private void NextLink_Click(object sender, RoutedEventArgs e)
        {
            Navigation.GoForward();
        }

        private void Navigation_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            BackLink.IsEnabled = false;
            NextLink.IsEnabled = false;

            if (Navigation.CanGoBack)
            {
                BackLink.IsEnabled = true;
            }

            if (Navigation.CanGoForward)
            {
                NextLink.IsEnabled = true;
            }

            if (e.Content is IPageProvider)
            {
                IPageProvider provider = e.Content as IPageProvider;
                TargetPage = provider.PageLevel;
                provider.Navigation = Navigation;
            }
        }

        private void OnLinkMouseEnter(object sender, MouseEventArgs e)
        {
            HyperlinkButton link = sender as HyperlinkButton;
            link.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 51, 51));
        }

        private void OnLinkMouseLeave(object sender, MouseEventArgs e)
        {
            HyperlinkButton link = sender as HyperlinkButton;
            link.Foreground = new SolidColorBrush(Color.FromArgb(255, 51, 102, 204));
        }


        private void SearchBtn_Click(object sender, RoutedEventArgs e)
        {
            //LightingContext.Singleton.QueryParameter = _queryModel.ConvertTo();
            //LightingContext.Singleton.MainPageNavigated = true;
            //if (Navigation.Content is LightingListView)
            //{
            //    LightingListView listView = (LightingListView)Navigation.Content;
            //    listView.Loading();
            //}
            //else
            //{
            //    LightingContext.Singleton.Navigation.Navigate(new Uri("/View/Level3/LightingListView.xaml", UriKind.RelativeOrAbsolute));
            //}
        }

        private async void Import_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = "灯具包 (*.zip;*.rar)|*.zip;*.rar";
            bool? result = fileDialog.ShowDialog();
            if (result.HasValue && result.Value)
            {
                byte[] bytes = null;
                using (Stream stream = fileDialog.File.OpenRead())
                {
                    bytes = Utility.ReadFully(stream);
                }

                try
                {
                    busy.IsBusy = true;
                    await TCPClient.Current.ConnectAsync();
                    byte[] response = await TCPClient.Current.Call(1, bytes);
                    busy.IsBusy = false;
                    MessageHelper.ShowMessage(response != null && response.Length > 0 && response[0] == (byte)1 ? "导入成功。" : "导入失败。");
                }
                catch (Exception ex)
                {
                    MessageHelper.ShowMessage("导入失败：" + ex.StackTrace + ex.Message);
                    busy.IsBusy = false;
                }
            }
        }

        private CondPordList GetCondProdList()
        {
            CondPordList.Builder builder = new CondPordList.Builder();
            if (!string.IsNullOrEmpty(ProductName.Text))
                builder.SetSeries(ProductName.Text);

            if (UseArea.SelectedIndex > 0)
            {
                ResItem resItem = (ResItem)UseArea.SelectedItem;
                builder.SetUsePlace(resItem.ItemID);
            }

            if (ProdType.SelectedIndex > 0)
            {
                ResItem resItem = (ResItem)ProdType.SelectedItem;
                builder.SetProdType(resItem.ItemID);
            }

            if (!string.IsNullOrEmpty(ProductVersion.Text))
                builder.SetProdVersion(ProductVersion.Text);

            if (ProductLable.SelectedIndex > 0)
                builder.SetProdLable((string)ProductLable.SelectedItem);

            if (LightingType.SelectedIndex > 0)
            {
                ResItem resItem = (ResItem)LightingType.SelectedItem;
                builder.SetAdpType(resItem.ItemID);
            }

            if (LSPowerStart.Value > 0)
                builder.SetStartLightingPower((int)LSPowerStart.Value);

            if (LSPowerEnd.Value > 0)
                builder.SetEndLightingPower((int)LSPowerEnd.Value);

            if (LSTemperature.SelectedIndex > 0)
                builder.SetColor(LSTemperature.SelectedIndex);

            if (LSCRI.SelectedIndex > 0)
                builder.SetCri(LSCRI.SelectedIndex);

            if (Angle.SelectedIndex > 0)
                builder.SetAngle(Angle.SelectedIndex);

            if (SetupType.SelectedIndex > 0)
            {
                ResItem resItem = (ResItem)SetupType.SelectedItem;
                builder.SetSetup(resItem.ItemID);
            }

            if (LSPowerStart.Value > 0)
                builder.SetStartMarketPrice((int)MarketPriceStart.Value);

            if (LSPowerEnd.Value > 0)
                builder.SetEndMarketPrice((int)MarketPriceEnd.Value);

            return builder.Build();
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
